package alg20250213;

public class Text3 {
    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        //1 创建表
        int[][] dp = new int[n + 1][n + 2];
        //2 初始化
        for (int i = 1; i <= n; i++) {
            dp[0][i] = dp[n + 1][i] = Integer.MAX_VALUE;
        }
        //3 填表
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i - 1][j]),
                        dp[i - 1][j + 1]) + matrix[i - 1][j - 1];
            }
        }
        //4 返回值
        int min = dp[n][n];
        for (int i = 1; i < n; i++) {
            if(dp[n][i] < min){
                min = dp[n][i];
            }
        }
        return min;

    }
}
